/**
 *
 */
package picounit.java.file;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.StringTokenizer;

import picounit.java.collection.Filter;
import picounit.java.collection.Iterable;
import picounit.java.type.Type;

public class ClassFile {
    @SuppressWarnings("deprecation")
    public ClassFile(Class<?> clazz) {
        URL resource = clazz.getResource('/' + clazz.getName().replace('.', '/') + ".class");

        this.clazz = clazz;
        this.file = new File(URLDecoder.decode(resource.getFile()));
    }

    public Iterable<Type> siblings() {
        return new Directory(file.getParentFile())
            .contents()
            .filter(CLASS_FILTER)
            .convert(sourceRoot());
    }

    private SourceRoot sourceRoot() {
        int packageDepth = new StringTokenizer(clazz.getName(), ".").countTokens();

        File sourceRoot = file;

        while (packageDepth-- > 0) {
            sourceRoot = sourceRoot.getParentFile();
        }

        return new SourceRoot(sourceRoot);
    }

    private final Class<?> clazz;
    private final File file;

    private static final Filter<File> CLASS_FILTER = new Filter<File>() {
        public boolean passes(File file) {
            return file.getName().endsWith(".class");
        }
    };
}